package light.im.loginserver;

import java.io.IOException;
import java.net.InetSocketAddress;
import org.json.JSONObject;

import light.im.IMEndpoint;
import light.im.loginserver.action.EchoAction;
import light.im.loginserver.action.LoginAction;
import light.network.Endpoint;
import light.network.EndpointHandlerAdapter;
import light.network.EndpointSession;
import light.network.PackProtocal;
import light.network.Packet;
import light.network.SendHandlerAdapter;
import light.network.UdpEndpoint;
import light.network.object.PackObject;

public class LoginServer {

	
	public LoginServer() throws IOException
	{
		IMEndpoint s = new IMEndpoint("localhost", 10606);
		s.registerAction(new LoginAction());
		s.registerAction(new EchoAction());
		s.start();
	}
	
	static class Unit
	{
		Packet data;
		InetSocketAddress target;
	}
	
	public static void main(String[] args) throws Exception {
		
		new LoginServer();
		
		JSONObject obj = new JSONObject().put("user", "haha").put("action", "login").put("psw", "haha");
		Endpoint ep = new UdpEndpoint();
		ep.start(new InetSocketAddress(33333));
		final Packet pacl = ep.allocatePacket(1024);
		ep.setReceiveHandler(new EndpointHandlerAdapter(){
			@Override
			public void onReceive(EndpointSession ep, Packet packet) {
				try {
					//FIXME 问题描述：传入的packet的position并不是9，应该从9开始才是可读状态
					PackObject ob = PackProtocal.wrap(packet);
					System.out.println(ob.getHeader());
					//System.out.println(new String(data.array(), data.start(), data.length()));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		pacl.put(obj.toString().getBytes());
		pacl.flip();
		ep.openSession(new InetSocketAddress("localhost", 10606), null, new SendHandlerAdapter() {
			@Override
			public void onSession(EndpointSession session, Object attachment) {
				try {
					session.send(pacl);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}
}
